package org.xq.softcup.mq.util;


import java.io.IOException;
import java.net.ServerSocket;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Slf4j
public class NetUtil {
    private static boolean used = false;
    public static int findAvailablePort(int defaultPort) throws Exception
    {
        int portTmp = defaultPort;
        while (portTmp < 65535)
        {
            if (!isPortUsed(portTmp)) {
                return portTmp;
            }
            portTmp++;
        }
        portTmp = defaultPort--;
        while (portTmp > 0)
        {
            if (!isPortUsed(portTmp)) {
                return portTmp;
            }
            portTmp--;
        }
        throw new Exception("端口不可用.");
    }

    public static boolean isPortUsed(int port)
    {
        used = false;
        ServerSocket serverSocket = null;
        try
        {
            serverSocket = new ServerSocket(port);
            return false;
        }
        catch (IOException e)
        {
            log.info("[{}] 端口已被使用.", Integer.valueOf(port));
            used = true;
        }
        finally
        {
            if (serverSocket != null) {
                try
                {
                    serverSocket.close();
                }
                catch (IOException e)
                {
                    log.info("");
                }
            }
        }
        return used;
    }
}
